/*
File: Plane.cpp
Desc: Contains the code definition for the plane class
*/

#include "Geometry.h"

/*
Function	: Constructor
Input Params: None
Return type	: None
Desc		: Initializes the plane object using point and normal form
*/
Plane::Plane(Vector3& _p, Vector3& _n)
{
	point = _p;
	normal = _n;
	// normalize normal
	normal.Normalize();
	// calculate distance from origin
	d = normal * point;
}

/*
Function	: Constructor
Input Params: @1 - Vector3 (1st point)
			  @2 - Vector3 (2nd point)
			  @3 - Vector3 (3rd point)
Return type	: None
Desc		: Plane initialization using the three point that lie on the plane
*/
Plane::Plane(Vector3& v1, Vector3& v2, Vector3& v3)
{
	// Assume any one point
	point = v1;
	// Calculate normal - assuming clockwise ordering of vertices
	normal = (v2-v1) ^ (v3-v1);
	normal.Normalize();
	// Calculate d
	d = normal * point;
}


/*
Function	: IntersectionTest
Input Params: @1 - Ray3 with which intersection test is to be performed
			  @2 - tmin - the lower bound of the intersection test
			  @3 - tmax - the upper bound of the intersection distance
			  @4 - IntersectionPacket(Ref) - the packet that contains information about the intersection test
Return type	: bool - Indicating yes/no result of intersection test
Desc		: This method computes the intersection test between the Ray and the plane
*/
bool Plane::IntersectionTest(Ray3& R, float tmin, float tmax, IntersectionPacket& pkt)
{
	// check if normal.ray_direction = 0 for this is the criteria when ray is parallel to plane or on the plane itself
	if(normal * R.direction == 0.0f) return false;
	else
	{
		float t = (d - (normal * R.origin))/(normal * R.direction);
		if(t < 0.0f && t <= tmin && t >= tmax) return false;	// boundary conditions - negative halfspace and [min-max] range
		else { pkt.t = t ; return true; }
	}
}